﻿/*
BF4Rcon.NET, provides a .NET implementation of BF4's RCON interface.
Copyright (C) 2013 Tim Marro

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace TimScripts.BF4Rcon
{
    public abstract class DynamicRconObject : DynamicObject
    {
        protected abstract string GetValue(string id);

        protected abstract IDictionary<string, string> Aliases { get; }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            bool r = false;
            string id = GetId(binder.Name);
            string value = GetValue(id);

            r = TryBool(value, out result) ||
                TryInt(value, out result) ||
                TryDouble(value, out result);

            if (!r) result = value;

            return true;
        }

        private string GetId(string binderName)
        {
            string result;

            if (!Aliases.TryGetValue(binderName, out result)) result = binderName;

            return result;
        }

        private static bool TryInt(string s, out object result)
        {
            int value;
            bool r = int.TryParse(s, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out value);

            if (r) result = value;
            else result = null;

            return r;
        }

        private static bool TryDouble(string s, out object result)
        {
            double value;
            bool r = double.TryParse(s, NumberStyles.Float, NumberFormatInfo.InvariantInfo, out value);

            if (r) result = value;
            else result = null;

            return r;
        }

        private static bool TryBool(string s, out object result)
        {
            bool value;
            bool r = bool.TryParse(s, out value);

            if (r) result = value;
            else result = null;

            return r;
        }
    }
}
